<script setup>
import { ref } from "vue";
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import {finduserService,deleteUserService,userRegisterService,sendVerificationCodeService} from "@/api/user.js"
//调用接口获取所有用户

const tableData = ref([]);

const query_argument=ref({
  userId: '',
  userName: '',
  email: ''
})

const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(3)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size
    pageNum.value = 1
    getUsers()

}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num
    getUsers()
}

// 搜索逻辑 => 按照最新的条件，重新检索，从第一页开始展示
const onSearch = () => {
  pageNum.value = 1 // 重置页面
  getUsers()
}

// 重置逻辑 => 将筛选条件清空，重新检索，从第一页开始展示
const onReset = () => {
  pageNum.value = 1 // 重置页面
  query_argument.value.userId = ''
  query_argument.value.userName = ''
  query_argument.value.email = ''
  getUsers()
}

const getUsers=async ()=>{
  console.log(pageNum.value)
  console.log(pageSize.value)
  const res=await finduserService(pageNum.value,pageSize.value,
  query_argument.value.userId,query_argument.value.userName,query_argument.value.email)
  tableData.value=res.data.list
  total.value=res.data.total
  console.log(res)
}
getUsers()

const handleDelete=(userId)=>{

    ElMessageBox.confirm(
    '确认删除?',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
    const res=await deleteUserService(userId)
    console.log(res)
    getUsers()
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
    })
}

const dialogVisible=ref(false)
const formModel = ref({
  userName: "",
  email: "",
  verification: "",
  password: "",
  resPassword: "",
});
const rules = {
  userName: [
    { required: true, message: "请输入昵称" },
    { min: 3, max: 5, message: "昵称长度需是3-15位" },
  ],
  password: [{ required: true, message: "请输入密码" },{min: 5,max:12,message:'密码长度需是5-12位'},],
  
  resPassword: [
    { required: true, message: "请再次输入密码" },
    {min: 5,max:12,message:'密码长度需是5-12位'},
    {
      validator: (rule, value, callback) => {
        if (formModel.value.password === formModel.value.resPassword) {
          callback();
        } else {
          callback(new Error("两次密码不一致"));
        }
      },
    },
  ],
  email: [
    { required: true, message: "请输入邮箱" },
    { type: "email", message: "邮箱格式不正确" },
  ],
  verification: [
    { required: true, message: "请输入邮箱验证码",trigger: "blur" }
  ]
};

const emailFormItem=ref()
const timer=ref()
const seconds=30
const currentSeconds=ref(seconds)
//调接口发送邮箱验证码
const sendEmailCode= async ()=>{
    if(timer.value){
        return 
    }
  await emailFormItem.value.validate()
  const res=await sendVerificationCodeService(formModel.value.email)
  console.log(res)
    timer.value=setInterval(() => {
        currentSeconds.value--
        if (currentSeconds.value === 0) {
          currentSeconds.value = seconds
          clearInterval(timer.value)
          timer.value = null
        }
      }, 1000)  
}

const ruleForm=ref()
//添加用户
const add=async ()=>{
  ruleForm.value.validate()
  const res=await userRegisterService(formModel.value)
  console.log(res)
  ElMessage.success('添加成功');
  dialogVisible.value=false
}



</script>
<template>

<el-card class="page-container">
    <template #header>
      <div class="header">
        <span>用户管理</span>
        <div class="extra">
            <el-button type="primary" @click="dialogVisible=true"> 添加用户 </el-button>
        </div>
      </div>
    </template>
    <el-form inline>

      <el-form-item label="id：">
        <el-input
                  v-model="query_argument.userId"
                  placeholder="请输入用户id"
                ></el-input>
      </el-form-item>
      <el-form-item label="邮箱：">
        <el-input
                  v-model="query_argument.email"
                  placeholder="请输入用户邮箱"
                ></el-input>
      </el-form-item>

      <el-form-item label="昵称：">
        <el-input
                  v-model="query_argument.userName"
                  placeholder="请输入用户昵称"
                ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="onSearch" type="primary">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%; margin-top: 30px">
        <el-table-column label="id" width="100" prop="userId"> 

        </el-table-column>
      <el-table-column label="头像" prop="avatar">
        <template #default="scope">
          <img width="38px" v-if="scope.row.avatar!='default.jpg'" :src="scope.row.avatar">
              <img v-else width="38px" src="@/assets/boy.jpg" />
      </template>
      </el-table-column>

      <el-table-column label="昵称" prop="userName"></el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      
    <el-table-column label="操作">
      <template #default="scope">
        <el-button
          size="small"
          type="danger"
          @click="handleDelete( scope.row.userId)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
    <template #empty>
        <el-empty v-if="tableData.length==0" description="空空如也" />
    </template>
  </el-table>
<div style="margin-top: 30px">
  <el-config-provider :locale="zhCn" >
    <el-pagination class="pag" v-if="tableData.length>0"  v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[2,3,5]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: left" />
    
  </el-config-provider>
</div>
  </el-card>
  

  <el-dialog
    v-model="dialogVisible"
    title="添加用户"
  >

  <div >
            <el-form 
            style="width: 500px; margin-left: 85px;"
              :model="formModel"
              :rules="rules"
              ref="ruleForm"
              label-position="left"
              label-width="auto"
            >
              <el-form-item prop="userName" label="昵称">
                <el-input
                  v-model="formModel.userName"
                  placeholder="请输入昵称"
                  
                ></el-input>
              </el-form-item>
              <el-form-item  ref="emailFormItem" prop="email" label="邮箱">
                <el-input
                  v-model="formModel.email"
                  placeholder="请输入邮箱"
                ></el-input>
              </el-form-item>
              <el-form-item prop="password" label="密码">
                <el-input
                  v-model="formModel.password"
                  placeholder="请输入密码"
                  show-password
                  
                ></el-input>
              </el-form-item>
              <el-form-item prop="resPassword" label="再次输入密码">
                <el-input
                  v-model="formModel.resPassword"
                  placeholder="请输再次输入密码"
                  show-password
                
                ></el-input>
              </el-form-item>
              <el-form-item prop="verification" label="邮箱验证码">
                <el-input
                  style="width: auto"
                  v-model="formModel.verification"
                  placeholder="请输邮箱验证码"
              
                ></el-input>
                
                <el-button :disabled='currentSeconds != seconds' @click="sendEmailCode()"   style="margin-left: 30px" plain
                  >{{currentSeconds === seconds ? '获取邮箱验证码' : currentSeconds+'秒后重新获取'}}</el-button
                >
               
              </el-form-item>
              
            </el-form>
          </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="add">
          添加
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.page-container {
  margin-top: 50px;
  min-height: 100%;
  box-sizing: border-box;
  position: relative;
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.pag {
  position: absolute;
  bottom: 0;
  margin-bottom: 20px;
}
</style>
